package com.tgy.algorithm._经典题目01;

import java.util.Arrays;
import java.util.TreeMap;

/**
 * 给你一个字符串类型的数组arr，
 * 譬如:
 * String[] arr = {"b\st","d\","a\d\e","a\b\c"}
 * a
 *   b
 *      c
 *   d
 * b
 *   st
 * d
 * 同一级的需要按字母顺序排列不能乱
 */
public class _021_路径打印 {

    static class DictTreeNode {
        public String value;
        public TreeMap<String,DictTreeNode> nodes;
        public DictTreeNode(String value) {
            this.value = value;
            this.nodes = new TreeMap<>();
        }
    }

    public static void printStrArr(String[] arrs) {
        if (arrs == null || arrs.length == 0) {
            return;
        }

        DictTreeNode root = new DictTreeNode("");
        for (String arr : arrs) {
            String[] strings = arr.split("\\\\");
            if (strings.length > 0) {
                add(root, strings);
            }
        }
        doPrintStrArr(root,0);
    }

    public static void doPrintStrArr(DictTreeNode root,int level) {

        if (level > 0) {
            System.out.println(generalSpace(level - 1) + root.value);
        }
        TreeMap<String, DictTreeNode> nodes = root.nodes;
        if (!nodes.isEmpty()) {
            nodes.forEach((key,val)->{
                doPrintStrArr(val,level+1);
            });
        }
    }

    public static String generalSpace(int level) {
        StringBuilder sb = new StringBuilder();
        int lastLevel = level << 2;
        for (int i = 0; i < lastLevel; i++) {
            sb.append(" ");
        }
        return sb.toString();
    }

    public static void add(DictTreeNode root, String[] arrs) {
        DictTreeNode node = root;
        for (String arr : arrs) {
            TreeMap<String, DictTreeNode> nodes = node.nodes;
            if (!nodes.containsKey(arr)) {
                node = new DictTreeNode(arr);
                nodes.put(arr,node);
            }else {
                node = nodes.get(arr);
            }
        }
    }

    public static void main(String[] args) {
        String[] arr = {"b\\st","d\\","a\\d\\e","a\\b\\c"};
        printStrArr(arr);
    }
}
